/**
 * rgba转化为8位16进制hex
 * @param rgba rgba或rgb字符串
 */
export function rgba2hex(rgba: string): string {
  rgba = rgba.replace(/rgba?|\r|\n|\s/g, '');
  const parsed = rgba.slice(1, -1).split(',');
  if (!parsed) {
    throw new Error(`Invalid format: ${rgba}`);
  }
  const red = parsed[0];
  const green = parsed[1];
  const blue = parsed[2];
  const alpha = parsed[3];
  const elems = [hex(red), hex(green), hex(blue)];
  if (alpha) {
    elems.push(alphaHex(alpha));
  }
  return `#${elems.join('')}`;

  function hex(number: string) {
    if (parseInt(number, 0) > 255) {
      throw new Error(`'${number}' is greater than 255(0xff);`);
    }
    const str = Number(number).toString(16);
    return (`0${str}`).slice(-2);
  }

  function alphaHex(number: any) {
    if (parseInt(number, 0) > 1) {
      throw new Error(`alpha:'${number}' is greater than 1;`);
    }
    const str = (~~(number * 0xff)).toString(16);
    return (`0${str}`).slice(-2);
  }
}

export function copyText(text: string): boolean {
  const parent = document.body;
  const el = document.createElement('input');
  el.value = text;
  Object.assign(el.style, {
    position: 'absolute',
    top: 0,
    right: 0,
    opacity: 0,
  });
  parent.appendChild(el);
  try {
    el.focus();
    el.setSelectionRange(0, -1);
    return document.execCommand('copy');
  } catch (e) {
    return false;
  } finally {
    parent.removeChild(el);
  }
}

/**
 * [装饰器]防止抖动
 * @param delay 延迟
 */
export function Debounce(delay = 300): any {
  return (
    target: Object,
    propertyKey: string,
    propertyDecorator: PropertyDescriptor,
  ): PropertyDescriptor => {
    const methods = propertyDecorator.value;
    let timer: any | null = null;
    propertyDecorator.value = function (...args: any): void {
      timer && clearTimeout(timer);
      timer = setTimeout(methods.bind(this, ...args), delay);
    };
    return propertyDecorator;
  };
}
